package org.wishwork.api.aftersale.refund;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.aftersale.refund.response.RefundQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 退货退款查询
 * @author: WangYX
 * @create: 2022-04-12 16:43
 * @Version: 1.0.0
 **/
public class RefundQueryApi extends Api<List<RefundQueryResponse>, RefundQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(RefundQueryApi.class);

    private Context context;

    public RefundQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(RefundQueryRequest refundQueryRequest) throws Exception {
        String url = "/open/refund/single/query";
        Map<String, Object> params = new HashMap<>();
        if (refundQueryRequest.getShopId() != null) {
            params.put("shop_id", refundQueryRequest.getShopId());
        }
        if (ObjectUtil.isNotEmpty(refundQueryRequest.getIsOfflineShop())) {
            params.put("is_offline_shop", refundQueryRequest.getIsOfflineShop());
        }
        if (refundQueryRequest.getSoIds() != null && refundQueryRequest.getSoIds().size() > 0) {
            params.put("so_ids", refundQueryRequest.getSoIds());
        }
        if (refundQueryRequest.getShopBuyerIds() != null && refundQueryRequest.getShopBuyerIds().size() > 0) {
            params.put("shop_buyer_ids", refundQueryRequest.getShopBuyerIds());
        }
        return HttpHelper.sendRequest(refundQueryRequest, params, url);
    }

    @Override
    protected List<RefundQueryResponse> process(JSONObject data, RefundQueryRequest refundQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<RefundQueryResponse> refundQueryResponses = datas.toJavaList(RefundQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = refundQueryRequest.getPageIndex();
            RefundQueryRequest build = refundQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<RefundQueryResponse> business = business(build);
            refundQueryResponses.addAll(business);
        }
        return refundQueryResponses;
    }
}
